package com.yumeng.framework.auth.security.authentication.normal;

import com.yumeng.common.helper.AssertHelper;
import com.yumeng.framework.auth.security.authentication.custom.CustomAbstractAuthenticationProcessingFilter;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

/**
 * 普通登录认证过滤器
 * 1、可在登录时加入除用户名、密码外的其他参数：登录客户端类型、验证码等等
 * @author wxd
 * @date 2025/3/3 14:34
 */
public class NormalLoginAuthenticationFilter extends CustomAbstractAuthenticationProcessingFilter {


    /** 参数名-用户名 */
    private String usernameParameter = "username";
    /** 参数名-密码 */
    private String passwordParameter = "password";

    private static final RequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER = PathPatternRequestMatcher.withDefaults().matcher(HttpMethod.POST, "/login");

    public NormalLoginAuthenticationFilter() {
        super(DEFAULT_ANT_PATH_REQUEST_MATCHER);
    }

    public NormalLoginAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(DEFAULT_ANT_PATH_REQUEST_MATCHER, authenticationManager);
    }

    @Override
    protected AbstractAuthenticationToken obtainAuthenticationToken(HttpServletRequest request) {
        String username = request.getParameter(this.usernameParameter);
        String password = request.getParameter(this.passwordParameter);
        username = (username != null) ? username.trim() : "";
        password = (password != null) ? password.trim() : "";
        return NormalLoginAuthenticationToken.unauthenticated(username, password);
    }

    @Override
    protected AbstractAuthenticationToken obtainAuthenticationTokenForJson(HttpServletRequest request) {
        throw new AuthenticationServiceException("暂未实现json格式传参模式");
    }


    public void setUsernameParameter(String usernameParameter) {
        AssertHelper.assertNotBlank(usernameParameter, "Username parameter must not be empty or null");
        this.usernameParameter = usernameParameter;
    }
    public void setPasswordParameter(String passwordParameter) {
        AssertHelper.assertNotBlank(passwordParameter, "Password parameter must not be empty or null");
        this.passwordParameter = passwordParameter;
    }

}
